﻿using System.Diagnostics.CodeAnalysis;
using Admin.CommonLib.Models.Permission;
using Admin.RazorLib.Services;
using Client.BlazorWasmApp.Models;
using Microsoft.AspNetCore.Components;

namespace Client.BlazorWasmApp.Shared;

public partial class SideMenu
{
    private IList<MenuModel> _menus = new List<MenuModel>();

    [Inject]
    [NotNull]
    public IPermissionService? PermissionService { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var result = await PermissionService.QueryPermissionsByCurrentUser(1);

        if (result.Succeeded)
        {
            GetMenuChild(result.Data, _menus);
        }

        await base.OnInitializedAsync();
    }

    private void GetMenuChild(IList<PermissionTreeResponseDto>? permissions, IList<MenuModel> menus)
    {
        if (permissions != null)
        {
            foreach (var permission in permissions)
            {
                var menuInfo = new MenuModel()
                {
                    Text = permission.Name,
                    Icon = permission.Icon,
                    Url = permission.Url
                };

                if (permission?.Children != null)
                {
                    menuInfo.Children = new List<MenuModel>();
                    GetMenuChild(permission.Children.ToList(), menuInfo.Children);
                }

                menus.Add(menuInfo);
            }
        }
    }
}